package com.plat.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.plat.dao.IBaseDao;
import com.plat.security.dao.SysResourcesDao;
import com.plat.security.entity.SysResources;
import com.plat.service.ISysResources;

@SuppressWarnings("unchecked")
@Service
public class SysResourcesImpl extends BaseServiceImpl<SysResources> implements ISysResources {

    @Autowired
    private SysResourcesDao dao;

    @Override
    public IBaseDao<SysResources> getDao() {
        return dao;
    }

    @Override
    public List<SysResources> findParentUrl(List<String> authNames) {
        String hql = "SELECT DISTINCT s FROM SysResources s,SysAuthoritiesResources a where s.resourceId = a.resourceId and s.level=1 and a.authorityId in(:authorityId)";
        Query query = dao.createQuery(hql);
        query.setParameterList("authorityId", authNames);
        List<SysResources> sysoutList = query.list();
        return sysoutList;
    }

    @Override
    public List<SysResources> findChildNodes(String pid, List<String> authNames) {
        String hql = "SELECT DISTINCT s FROM SysResources s,SysAuthoritiesResources a where s.resourceId = a.resourceId and s.pid=:pid and a.authorityId in(:authorityId)";
        Query query = dao.createQuery(hql);
        query.setParameter("pid", pid);
        query.setParameterList("authorityId", authNames);
        List<SysResources> sysoutList = query.list();
        return sysoutList;
    }

    @Override
    public void save(Object o) {
        SysResources res = (SysResources) o;
        //一级菜单
        if (1 == res.getLevel()) {
            Criteria cri = getDao().createCriteria(Restrictions.eq("level", 1));
            cri.setProjection(Projections.max("resourceId"));
            String max = (String) cri.uniqueResult();
            Long nextResourceId = Long.valueOf(max) + 1;
            res.setResourceId(nextResourceId.toString());
        } else {
            Criteria cri = getDao().createCriteria(Restrictions.gt("level", 1));
            cri.add(Restrictions.eq("pid", res.getPid()));
            cri.setProjection(Projections.max("resourceId"));
            String max = (String) cri.uniqueResult();
            Long nextResourceId = 0L;
            if (StringUtils.isEmpty(max)) {
                nextResourceId = Long.valueOf(res.getPid().toString() + "100");
            } else {
                nextResourceId = Long.valueOf(max) + 1;
            }
            res.setResourceId(nextResourceId.toString());
        }
        super.save(o);
    }
}
